package com.le.tester.imooc.masterJUC.lock.spinlock;

import java.util.concurrent.atomic.AtomicReference;

/**
 * 描述：自旋锁
 */
public class SpinLock {
    private static AtomicReference<Thread> sign = new AtomicReference<>();

    public void lock() {
        Thread currentThread = Thread.currentThread();
        //原子引用赋予了当前的线程,自选锁的实现，一直的使用while,也就是一直的尝试
        //获取不到锁的话，就一直的自旋
        while (!sign.compareAndSet(null, currentThread)) {
            System.out.println("自旋获取失败，再次尝试");
        }

    }

    public void unlock() {
        Thread currentThread = Thread.currentThread();
        sign.compareAndSet(currentThread, null);
    }

    public static void main(String[] args) {
        SpinLock spinLock = new SpinLock();
        Runnable runnable = () -> {
            System.out.println(Thread.currentThread().getName() + " 开始尝试的获取自旋锁");
            spinLock.lock();
            System.out.println(Thread.currentThread().getName() + " 获取到了自旋锁");
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                System.out.println(Thread.currentThread().getName() + " 释放自旋锁");
                spinLock.unlock();
            }
        };
        Thread thread1 = new Thread(runnable);
        Thread thread2 = new Thread(runnable);
        thread1.start();
        thread2.start();
    }


}
